package com.zxmr.hospital.info.action;

import java.util.List;

import com.alibaba.fastjson.JSON;
import com.zxmr.action.Request;
import com.zxmr.action.Response;
import com.zxmr.action.ResponsePayload;
import com.zxmr.action.ResultCode;
import com.zxmr.domain.Item;
import com.zxmr.domain.ItemPrice;
import com.zxmr.domain.account.User;
import com.zxmr.domain.service.ItemService;
import com.zxmr.hospital.info.action.dto.ItemDTO;
import com.zxmr.navigate.ExecuteException;
import com.zxmr.navigate.Executor;
import com.zxmr.util.ResourceManager;
import com.zxmr.util.UserTraceManager;
import com.zxmr.util.Utils;

/**
 * add hospital service item
 * @author wenkuany
 *
 */
public class ItemAction extends Executor{

	enum method{
		add,
		query,
		queryAll,
		update,
		delete
	}
	@Override
	public void execute(Request request, Response response) {
		
		method m = Enum.valueOf(method.class, this.getElement().getMethod());
		try
		{
			switch(m)
			{
			case add:
				add(request,response);
				break;
			case query:
				query(request,response);
				break;
			case queryAll:
				queryAll(request,response);
				break;
			case update:
				update(request,response);
				break;
			case delete:
				delete(request,response);
				break;
			}
		}catch(Exception e)
		{
			if(e instanceof ExecuteException)
			{
				ResponsePayload payload = new ResponsePayload(e.getMessage());
				response.setPayload(payload);
				response.setResult(ResultCode.COMPONENT_ERROR);
			}else
			{
				e.printStackTrace();
				this.internalErrorResponse(response);
			}
		}
	}
	public void query(Request request,Response response)throws ExecuteException
	{
		ItemService service = new ItemService();
		int id = parseItemID(request);
		
		Item item = service.queryItem(id);
		validate(request.getAccount(),item);
		
		List<ItemPrice> prices = service.loadAllPrice(item.getId());
		
		ItemDTO dto = itemToDTO(item);
		dto.setPriceList(prices);
		
		ResponsePayload payload = new ResponsePayload(JSON.toJSONString(dto));
		response.setPayload(payload);
	}
	private ItemDTO itemToDTO(Item item)
	{
		ItemDTO dto = new ItemDTO();
		dto.setId(item.getId());
		dto.setAddUser(item.getAddUser());
		dto.setDescription(item.getDescription());
		dto.setLastEditUser(item.getLastEditUser());
		dto.setName(item.getName());
		dto.setPriceValue(item.getPriceValue());
		
		return dto;
	}
	public void delete(Request request,Response response)throws ExecuteException
	{
		ItemService service = new ItemService();
		int id = parseItemID(request);
		
		Item item = service.queryItem(id);
		validate(request.getAccount(),item);
		
		if(!service.deleteItem(item))
			this.internalErrorResponse(response);
		else
		{
			String action = ResourceManager.getInstance().getMessage("com.zxmr.info.deleteItem",item.getName());
			UserTraceManager.addTrace(action, request.getAccount());
		}
		
	}
	private int parseItemID(Request request)throws ExecuteException
	{
		try
		{
			return Integer.parseInt(request.getRequestParameters().get("id"));
		}catch(Exception e)
		{
			e.printStackTrace();
			throw new ExecuteException(ResourceManager.getInstance().getMessage("com.zxmr.info.errorPara"));
		}
	}
	public void update(Request request,Response response)throws ExecuteException
	{
		ItemService service = new ItemService();
		
		ItemDTO dto = parseItem(request);
		Item old = service.queryItem(dto.getId());
		
		validate(request.getAccount(),old);
		
		validateUpdateItem(dto,old);
		
		old.setLastEditUser(request.getAccount().getName());
		
		if(!service.updateItem(old))
		{
			this.internalErrorResponse(response);
		}else
		{
			String action = ResourceManager.getInstance().getMessage("com.zxmr.info.updateItem",old.getName());
			UserTraceManager.addTrace(action, request.getAccount());
		}
	}
	public void validate(User user,Item item)throws ExecuteException
	{
		if(item == null || item.getCompany()!= user.getCompany())
			throw new ExecuteException(ResourceManager.getInstance().getMessage("com.zxmr.info.noauth"));
	}
	public void validateUpdateItem(ItemDTO dto,Item item)throws ExecuteException
	{
		if(dto == null)throw new ExecuteException(ResourceManager.getInstance().getMessage("com.zxmr.info.errorPara"));
		if(Utils.isStringEmptyWithTrim(dto.getName()))throw new ExecuteException(ResourceManager.getInstance().getMessage("com.zxmr.info.noname"));
		
		item.setName(dto.getName());
		item.setDescription(dto.getDescription());
		item.setPriceValue(dto.getPriceValue());
	}
	public void queryAll(Request request,Response response)throws ExecuteException
	{
		ItemService service = new ItemService();
		List<Item> items = service.queryItems(request.getAccount().getCompany());
		ResponsePayload payload = new ResponsePayload(JSON.toJSONString(items));
		response.setPayload(payload);
	}
	public void add(Request request,Response response)throws ExecuteException
	{
		ItemService service = new ItemService();
		
		ItemDTO dto = parseItem(request);
		Item item = validateAddItem(dto,request.getAccount().getCompany());
		setFixedField(item,request);
		
		if(!service.addItem(item))
		{
			this.internalErrorResponse(response);
		}else
		{
			String action = ResourceManager.getInstance().getMessage("com.zxmr.info.addItem",item.getName());
			UserTraceManager.addTrace(action, request.getAccount());
		}
	}
	private void setFixedField(Item item,Request request)
	{
		item.setAddUser(request.getAccount().getName());
		item.setCompany(request.getAccount().getCompany());
	}
	private Item validateAddItem(ItemDTO dto,int company)throws ExecuteException
	{
		if(dto == null)throw new ExecuteException(ResourceManager.getInstance().getMessage("com.zxmr.info.errorPara"));
		if(Utils.isStringEmptyWithTrim(dto.getName()))throw new ExecuteException(ResourceManager.getInstance().getMessage("com.zxmr.info.noname"));
		
		ItemService service = new ItemService();
		Item it = service.queryItem(dto.getName(), company);
		if(it != null)throw new ExecuteException(ResourceManager.getInstance().getMessage("com.zxmr.info.item.name.exist",dto.getName()));
		
		
		Item item = new Item();
		item.setName(dto.getName());
		item.setDescription(dto.getDescription());
		item.setPriceValue(dto.getPriceValue());
		return item;
	}
	private ItemDTO parseItem(Request request)throws ExecuteException
	{
		try
		{
			return JSON.parseObject(request.getRequestParameters().get("parameters"), ItemDTO.class);
		}catch(Exception e)
		{
			throw new ExecuteException(ResourceManager.getInstance().getMessage("com.zxmr.info.errorPara"));
		}
	}
}
